/**
 * ContactActivity.java
 * 
 * Create Version: 1.0
 * Author: lixh
 * Create Date: 2014-9-6
 * 
 * Copyright (c) 2014 CQCIS. All Right Reserved.
 */
package com.yinhai.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Stack;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.listener.MsgTextLongClickListener;
import com.yinhai.adapter.ContactAdpter;
import com.yinhai.asynctask.BaseTask;
import com.yinhai.constant.ChatConstant;
import com.yinhai.constant.Contact;
import com.yinhai.model.ContactGroup;
import com.yinhai.model.ContactsUser;
import com.yinhai.model.MsgModel;
import com.yinhai.model.UserUserContact;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.util.NullUtils;
import com.yinhai.util.Util;

/**
 * ContactActivity （人员选择界面）
 * 
 * @author lixh
 */
public class ContactActivity extends Activity implements OnScrollListener {
    private ListView groupListView;
    
    private ContactAdpter smsAdpter;
    
    private ContactUserServiceImpl contactUserService;
    
    private EditText editText;
    
    private CheckBox checkBox;
    
    private ImageView head_btn_back;
    
    private Stack<String> parentIds = new Stack<String>();
    
    private List<UserUserContact> datas = new ArrayList<UserUserContact>();
    
    private int userType = 0;// 0:全部 1：本地通讯 2：集团通讯 3:聊天选择
    
    private boolean isMutiCheck = false;// 是否多选
    
    private int userSize = 20;// 选择人员的数量
    
    // private List<UserUserContact> selectDatas = new ArrayList<UserUserContact>();
    private Map<String, UserUserContact> selectDatas = new HashMap<String, UserUserContact>();
    
    private MsgModel resendMsgModel;
    
    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_contact);
        
        userType = getIntent().getIntExtra("userType", 0);
        isMutiCheck = getIntent().getBooleanExtra("isMutiCheck", false);
        userSize = getIntent().getIntExtra("userSize", userSize);
        if (getIntent().hasExtra(MsgTextLongClickListener.SER_KEY)) {
            resendMsgModel = (MsgModel)getIntent().getSerializableExtra(MsgTextLongClickListener.SER_KEY);
        }
        
        if (userType == 3) {
            isMutiCheck = false;
        }
        
        findViewById(R.id.btn_select).setVisibility(isMutiCheck ? View.VISIBLE : View.GONE);
        findViewById(R.id.contact_check).setVisibility(isMutiCheck ? View.VISIBLE : View.GONE);
        TextView textView = (TextView)this.findViewById(R.id.txt_contact);
        textView.setText("人员选择");
        editText = (EditText)this.findViewById(R.id.search_txt);
        checkBox = (CheckBox)this.findViewById(R.id.search_cb);
        groupListView = (ListView)this.findViewById(R.id.contact_group_list_item);
        head_btn_back = (ImageView)this.findViewById(R.id.head_btn_back);
        head_btn_back.setVisibility(View.VISIBLE);
        contactUserService = new ContactUserServiceImpl(this);
        smsAdpter = new ContactAdpter(this, datas, isMutiCheck);
        
        groupListView.setOnScrollListener(this);
        
        groupListView.setAdapter(smsAdpter);
        
        groupListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UserUserContact userContact = (UserUserContact)smsAdpter.getItem(position);
                // 部门
                if (userContact.getType().equals(Contact.CONTACT_TYPE_GROUP)) {
                    if (userType == 3 && userContact.getId().equals("-1")) {
                        Intent intent = new Intent(ContactActivity.this, ChatGroupActivity.class);
                        if (resendMsgModel != null) {
                            Bundle mBundle = new Bundle();
                            mBundle.putSerializable(MsgTextLongClickListener.SER_KEY, resendMsgModel);
                            intent.putExtras(mBundle);
                        }
                        startActivity(intent);
                        finish();
                    } else {
                        findData(null, userContact.getId(), "user");
                    }
                } else {
                    if (isMutiCheck) {
                        selectCheck(userContact);
                        // 跳转
                    } else {
                        if (userType == 3) {
                            Intent intent = new Intent(ContactActivity.this, ChatActivity.class);
                            intent.putExtra("receID", userContact.getPhone());
                            intent.putExtra("receName", userContact.getName());
                            intent.putExtra("type", 1);// 1:一对一；2：部门；3：群组
                            ChatConstant.CURRENT_CHAT = "1";
                            ChatConstant.CURRENT_CHART_ID = userContact.getPhone();
                            if (resendMsgModel != null) {
                                Bundle mBundle = new Bundle();
                                mBundle.putSerializable(MsgTextLongClickListener.SER_KEY, resendMsgModel);
                                intent.putExtras(mBundle);
                            }
                            startActivity(intent);
                            finish();
                        } else {
                            Intent intent = new Intent();
                            ContactsUser contactsUser = new ContactsUser();
                            contactsUser.setId(Integer.valueOf(userContact.getId()));
                            contactsUser.setName(userContact.getName());
                            contactsUser.setTelPhone(userContact.getPhone());
                            contactsUser.setImUserName(userContact.getImUserName());
                            intent.putExtra("data", (Serializable)contactsUser);
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    }
                }
                
            }
        });
        editText.addTextChangedListener(new TextWatcher() {
            
            @Override
            public void afterTextChanged(Editable arg0) {
                String content = arg0.toString();
                if (NullUtils.isEmpty(content)) {
           
                    
                    if (userType == 1) {
                        findData(null, Contact.LOCAL_CONTACT_GROUP_ID, "user");
                    } else{
                        findData(null, parentIds.isEmpty()?"0":parentIds.pop(), "user");
                        }
                    return;
                }
                findData(arg0.toString(), null, "user");
                
            }
            
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }
            
            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
                
            }
            
        });
        //
        checkBox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(CompoundButton button, boolean isChecked) {
                
                editText.setText("");
            }
            
        });
        head_btn_back.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View ediview) {
                onBackPressed();
            }
        });
        if (userType == 1) {
            findData(null, Contact.LOCAL_CONTACT_GROUP_ID, "user");
        } else
            findData(null, "0", "user");
    }
    
    public void onBackPressed() {
        if (NullUtils.isNotEmpty(editText.getText().toString())) {
            parentIds.pop();
            editText.setText("");
            return;
        }
        if (parentIds.isEmpty()) {
            super.onBackPressed();
            return;
        }
        parentIds.pop();
        if (parentIds.isEmpty()) {
            super.onBackPressed();
            return;
        }
        String value = parentIds.pop();
        if (value.contains("select")) {
            findData(value.substring(6), null, "user");
        } else {
            findData(null, value, "user");
        }
        
    }
    
    private void findData(String... params) {
        
        String value = "";
        if (!parentIds.isEmpty()) {
            value = parentIds.lastElement();
        }
        
        if (params != null && NullUtils.isNotEmpty(params[0])) {
            if (value.contains("select") && !parentIds.isEmpty()) {
                parentIds.pop();
            }
            parentIds.add("select" + params[0]);
        } else {
            parentIds.add(params[1]);
        }
        
        new BaseTask<String, String, List<UserUserContact>>(this) {
            
            @Override
            protected void onSuccess(List<UserUserContact> result) {
                smsAdpter.removeAll();
                smsAdpter.notifyDataSetChanged();
                if (userType == 3 && !parentIds.isEmpty() && parentIds.lastElement().equals("0")) {
                    UserUserContact userContact = new UserUserContact();
                    userContact.setId("-1");
                    userContact.setName("发起群聊");
                    userContact.setNum("");
                    userContact.setType(Contact.CONTACT_TYPE_GROUP);
                    userContact.setMatchType(Contact.MATCH_NAME);
                    datas.add(userContact);
                }
                for (UserUserContact userContact : result) {
                    if (NullUtils.isEmpty(userContact.getId())) {
                        userContact.setId("l" + userContact.getPhone());
                    }
                    String key = "";
                    if (userContact.getType().equals(Contact.CONTACT_TYPE_GROUP)) {
                        key = "o" + userContact.getId();
                    } else {
                        key = "u" + userContact.getId();
                    }
                    userContact.setCheck(selectDatas.containsKey(key));
                }
                smsAdpter.addCollection(result);
                smsAdpter.notifyDataSetChanged();
            }
            
            @Override
            protected List<UserUserContact> doInBack(String... params)
                throws Exception {
                List<UserUserContact> list = new ArrayList<UserUserContact>();
                
                if (params != null && params.length == 3) {
                    list.addAll(contactUserService.searchContactUser(params[0],
                        params[1],
                        null,
                        userType != 3 ? userType : 2));
                }
                if (NullUtils.isEmpty(params[0]) || checkBox.isChecked() && NullUtils.isNotEmpty(params[0])) {
                    list.addAll(contactUserService.searchNewGroup(params[0], params[1], null, userType != 3 ? userType
                        : 2));
                }
                return list;
            }
        }.execute(params);
    }
    
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        
    }
    
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }
    
    public void selectCheck(UserUserContact userContact) {
        int i = 0;
        for (Entry<String, UserUserContact> entry : selectDatas.entrySet()) {
            if (entry.getKey().contains("u")) {
                i++;
            }
        }
        String key = "";
        if (userContact.getType().equals(Contact.CONTACT_TYPE_GROUP)) {
            key = "o" + userContact.getId();
            
        } else {
            key = "u" + userContact.getId();
        }
        if (!userContact.isCheck()) {
            
            if (i >= userSize) {
                Util.showMsg(this, "人员数量超过上线(" + userSize + ")");
                smsAdpter.notifyDataSetChanged();
                return;
            }
            
            if (userContact.getType().equals(Contact.CONTACT_TYPE_GROUP)) {
                if (Integer.valueOf(userContact.getNum()) + i > userSize) {
                    Util.showMsg(this, "人员数量超过上线(" + userSize + ")");
                    smsAdpter.notifyDataSetChanged();
                    return;
                }
            }
            
            selectDatas.put(key, userContact);
            if (userContact.getType().equals(Contact.CONTACT_TYPE_GROUP)) {
                Map<String, ContactsUser> userMap = new HashMap<String, ContactsUser>();
                Map<String, ContactGroup> groupMap = new HashMap<String, ContactGroup>();
                contactUserService.findDeptAllPersonAndDep(userMap, groupMap, userContact.getId());
                for (Entry<String, ContactsUser> entry : userMap.entrySet()) {
                    UserUserContact contact = new UserUserContact();
                    contact.setId(entry.getValue().getUserid() + "");
                    contact.setPhone(entry.getValue().getTelPhone());
                    contact.setImUserName(entry.getValue().getImUserName());
                    contact.setName(entry.getValue().getName());
                    contact.setParent_id(entry.getValue().getGroupId());
                    selectDatas.put("u" + contact.getId(), contact);
                }
                for (Entry<String, ContactGroup> entry : groupMap.entrySet()) {
                    UserUserContact contact = new UserUserContact();
                    contact.setId(entry.getValue().getGroupId() + "");
                    contact.setName(entry.getValue().getName());
                    contact.setParent_id(entry.getValue().getParent_id());
                    selectDatas.put("o" + contact.getId(), contact);
                }
            }
        } else {
            if (userContact.getType().equals(Contact.CONTACT_TYPE_GROUP)) {
                // 删除勾选子部门和人员
                removeChildren(userContact.getId());
            } else {
                // 删除上级部门的勾选
                removeDept(userContact.getParent_id());
            }
            selectDatas.remove(key);
        }
        userContact.setCheck(!userContact.isCheck());
        smsAdpter.notifyDataSetChanged();
    }
    
    private void removeChildren(String parentID) {
        Iterator<Map.Entry<String, UserUserContact>> ite = selectDatas.entrySet().iterator();
        List<String> keys = new ArrayList<String>();
        while (ite.hasNext()) {
            Map.Entry<String, UserUserContact> entry = ite.next();
            UserUserContact contact = entry.getValue();
            if (parentID.equals(contact.getParent_id())) {
                keys.add(entry.getKey());
            }
        }
        for (String str : keys) {
            UserUserContact contact = selectDatas.get(str);
            selectDatas.remove(str);
            removeChildren(contact.getId());
        }
        
    }
    
    private void removeDept(String parentID) {
        if (selectDatas.containsKey("o" + parentID)) {
            UserUserContact contact = selectDatas.get("o" + parentID);
            selectDatas.remove("o" + parentID);
            removeDept(contact.getParent_id());
        }
    }
    
    public void doSelect(View view) {
        List<ContactsUser> contacts = new ArrayList<ContactsUser>();
        for (Entry<String, UserUserContact> entry : selectDatas.entrySet()) {
            if (entry.getKey().contains("u")) {
                ContactsUser user = new ContactsUser();
                user.setUserid(entry.getValue().getId());
                user.setName(entry.getValue().getName());
                user.setTelPhone(entry.getValue().getPhone());
                user.setImUserName(entry.getValue().getImUserName());
                contacts.add(user);
            }
        }
        Intent intent = new Intent();
        intent.putExtra("data", (Serializable)contacts);
        setResult(RESULT_OK, intent);
        finish();
    }
    
    public void doAllCheck(View view) {
        if (((CheckBox)view).isChecked()) {
            int i = 0;
            for (Entry<String, UserUserContact> entry : selectDatas.entrySet()) {
                if (entry.getKey().contains("u")) {
                    i++;
                }
            }
            for (UserUserContact contact : datas) {
                if (contact.getType().equals(Contact.CONTACT_TYPE_GROUP)) {
                    if (!contact.isCheck()) {
                        i += Integer.valueOf(contact.getNum());
                    }
                    
                } else {
                    if (!contact.isCheck()) {
                        i++;
                    }
                }
                if (i > userSize) {
                    break;
                }
            }
            if (i > userSize) {
                ((CheckBox)view).setChecked(false);
                Util.showMsg(this, "人员数量超过上线(" + userSize + ")");
                return;
            }
            Map<String, UserUserContact> temp = new HashMap<String, UserUserContact>();
            for (UserUserContact contact : datas) {
                if (contact.getType().equals(Contact.CONTACT_TYPE_GROUP)) {
                    if (!contact.isCheck()) {
                        contact.setCheck(true);
                        temp.put("o" + contact.getId(), contact);
                        Map<String, ContactsUser> userMap = new HashMap<String, ContactsUser>();
                        Map<String, ContactGroup> groupMap = new HashMap<String, ContactGroup>();
                        contactUserService.findDeptAllPersonAndDep(userMap, groupMap, contact.getId());
                        for (Entry<String, ContactsUser> entry : userMap.entrySet()) {
                            UserUserContact userUserContact = new UserUserContact();
                            userUserContact.setId(entry.getValue().getUserid() + "");
                            userUserContact.setPhone(entry.getValue().getTelPhone());
                            userUserContact.setImUserName(entry.getValue().getImUserName());
                            userUserContact.setName(entry.getValue().getName());
                            userUserContact.setParent_id(entry.getValue().getGroupId());
                            temp.put("u" + userUserContact.getId(), userUserContact);
                        }
                        for (Entry<String, ContactGroup> entry : groupMap.entrySet()) {
                            UserUserContact userUserContact = new UserUserContact();
                            userUserContact.setId(entry.getValue().getGroupId() + "");
                            userUserContact.setName(entry.getValue().getName());
                            userUserContact.setParent_id(entry.getValue().getParent_id());
                            temp.put("o" + userUserContact.getId(), userUserContact);
                        }
                    }
                } else {
                    if (!contact.isCheck()) {
                        contact.setCheck(true);
                        temp.put("u" + contact.getId(), contact);
                    }
                }
            }
            selectDatas.putAll(temp);
        } else {
            for (UserUserContact contact : datas) {
                if (contact.getType().equals(Contact.CONTACT_TYPE_GROUP)) {
                    if (contact.isCheck()) {
                        contact.setCheck(false);
                        removeChildren(contact.getId());
                        selectDatas.remove("o" + contact.getId());
                    }
                } else {
                    if (contact.isCheck()) {
                        contact.setCheck(false);
                        // 删除上级部门的勾选
                        removeDept(contact.getParent_id());
                        selectDatas.remove("u" + contact.getId());
                    }
                }
            }
        }
        smsAdpter.notifyDataSetChanged();
    }
    
}
